package com.wzy.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class MyLB implements LoadBalance {
    AtomicInteger integer = new AtomicInteger();

    public final int getAndIncrement() {
        int current;
        int next;
        for (; ; ) {
            current = this.integer.get();
            next = current >= Integer.MAX_VALUE ? 0 : current + 1;
            if (this.integer.compareAndSet(current, next)) {
                System.out.println(">>>>>next" + next);
                return next;
            }
        }
    }

    @Override
    public ServiceInstance Instance(List<ServiceInstance> serviceInstances) {
        int index = getAndIncrement() % serviceInstances.size();
        return serviceInstances.get(index);
    }
}
